package com.yihu.wlyy.web.common;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.ImageCompress;
import com.yihu.wlyy.util.SystemConf;
import com.yihu.wlyy.web.BaseController;

@Controller
@RequestMapping(value = "/upload")
public class FileUploadController extends BaseController {

	/** 
	 * 图片上传 
	 * @return 
	 * @throws IOException  
	 * @throws IllegalStateException  
	 */
	@RequestMapping(value = "image", method = RequestMethod.POST/* , headers = "Accept=image/png" */)
	@ResponseBody
	public String image(HttpServletRequest request, HttpServletResponse response) {
		// 圖片列表
		List<File> images = new ArrayList<File>();
		List<String> tempPaths = new ArrayList<String>();
		// 文件保存的临时路径
		String tempPath = SystemConf.getInstance().getTempPath() + File.separator;
		// 拼接年月日路径
		String datePath = DateUtil.getStringDate("yyyy") + File.separator + DateUtil.getStringDate("MM") + File.separator + DateUtil.getStringDate("dd") + File.separator;
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
			// 创建文件夹
			File file = new File(tempPath + datePath);
			if (!file.exists()) {
				file.mkdirs();
			}
			String fileName = null;
			for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
				// 上传文件
				MultipartFile mf = entity.getValue();
				fileName = mf.getOriginalFilename();
				String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
				// 重命名文件
				SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
				String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
				File uploadFile = new File(tempPath + datePath + newFileName);
				// 拷贝文件流到指定文件路径
				FileCopyUtils.copy(mf.getBytes(), uploadFile);
				// 生成缩略图
				ImageCompress.compress(uploadFile.getAbsolutePath(), uploadFile.getAbsolutePath() + "_small", 300, 300);
				// 添加到上传成功数组中
				images.add(uploadFile);
				tempPaths.add(datePath + newFileName);
			}
			String urls = "";
			for (String image : tempPaths) {
				if (urls.length() == 0) {
					urls = image;
				} else {
					urls += "," + image;
				}
			}
			JSONObject json = new JSONObject();
			json.put("status", 200);
			json.put("msg", "上传成功");
			// 图片标识对象的HTTP链接
			json.put("urls", urls);
			System.out.println("图片上传：" + json.toString());
			return json.toString();
		} catch (Exception e) {
			error(e);
			try {
				// 清除垃圾图片
				for (File file : images) {
					FileUtils.forceDelete(file);
				}
			} catch (Exception e2) {
				error(e2);
			}
			return error(-1, "上传失败");
		}
	}

	/** 
	 * 聊天附件上传
	 * @return 
	 * @throws IOException  
	 * @throws IllegalStateException  
	 */
	@RequestMapping(value = "chat", method = RequestMethod.POST)
	@ResponseBody
	public String chatFile(HttpServletRequest request, HttpServletResponse response) {
		// 圖片列表
		List<File> files = new ArrayList<File>();
		List<String> tempPaths = new ArrayList<String>();
		// 获取聊天文件保存路径
		String tempPath = SystemConf.getInstance().getChatPath() + File.separator;
		// 拼接年月日路径
		String datePath = DateUtil.getStringDate("yyyy") + File.separator + DateUtil.getStringDate("MM") + File.separator + DateUtil.getStringDate("dd") + File.separator;
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
			// 创建文件夹
			File file = new File(tempPath + datePath);
			if (!file.exists()) {
				file.mkdirs();
			}
			String fileName = null;
			for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
				// 上传文件
				MultipartFile mf = entity.getValue();
				fileName = mf.getOriginalFilename();
				String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
				// 重命名文件
				SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
				String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
				File uploadFile = new File(tempPath + datePath + newFileName);
				// 拷贝文件流到指定文件路径
				FileCopyUtils.copy(mf.getBytes(), uploadFile);
				// 添加到上传成功数组中
				files.add(uploadFile);
				tempPaths.add(datePath + newFileName);
			}
			String urls = "";
			for (String temp : tempPaths) {
				if (urls.length() == 0) {
					urls = SystemConf.getInstance().getChatServer() + temp;
				} else {
					urls += "," + SystemConf.getInstance().getChatServer() + temp;
				}
			}
			JSONObject json = new JSONObject();
			json.put("status", 200);
			json.put("msg", "上传成功");
			// 图片标识对象的HTTP链接
			json.put("urls", urls);
			System.out.println("附件上传：" + json.toString());
			return json.toString();
		} catch (Exception e) {
			error(e);
			try {
				// 清除垃圾图片
				for (File file : files) {
					FileUtils.forceDelete(file);
				}
			} catch (Exception e2) {
				error(e2);
			}
			return error(-1, "上传失败");
		}
	}

	/**
	 * 语音上传
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "voice", method = RequestMethod.POST)
	@ResponseBody
	public String voice(HttpServletRequest request, HttpServletResponse response) {
		// 圖片列表
		List<File> voices = new ArrayList<File>();
		List<String> tempPaths = new ArrayList<String>();
		// 文件保存的临时路径
		String tempPath = SystemConf.getInstance().getTempPath() + File.separator;
		// 拼接年月日路径
		String datePath = DateUtil.getStringDate("yyyy") + File.separator + DateUtil.getStringDate("MM") + File.separator + DateUtil.getStringDate("dd") + File.separator;
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
			// 创建文件夹
			File file = new File(tempPath + datePath);
			if (!file.exists()) {
				file.mkdirs();
			}
			String fileName = null;
			for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
				// 上传文件
				MultipartFile mf = entity.getValue();
				fileName = mf.getOriginalFilename();
				String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
				// 重命名文件
				SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
				String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
				File uploadFile = new File(tempPath + datePath + newFileName);
				// 拷贝文件流到指定文件路径
				FileCopyUtils.copy(mf.getBytes(), uploadFile);
				// 添加到上传成功数组中
				voices.add(uploadFile);
				tempPaths.add(datePath + newFileName);
			}
			String urls = "";
			for (String voice : tempPaths) {
				if (urls.length() == 0) {
					urls = voice;
				} else {
					urls += "," + voice;
				}
			}
			JSONObject json = new JSONObject();
			json.put("status", 200);
			json.put("msg", "上传成功");
			// 图片标识对象的HTTP链接
			json.put("urls", urls);
			System.out.println("语音上传：" + json.toString());
			return json.toString();
		} catch (Exception e) {
			error(e);
			try {
				// 清除垃圾图片
				for (File file : voices) {
					FileUtils.forceDelete(file);
				}
			} catch (Exception e2) {
				error(e2);
			}
			return error(-1, "上传失败");
		}
	}

}
